package io.hellsinger.vortex.ui.component

import android.view.View
import android.view.View.MeasureSpec
import android.view.ViewGroup
import kotlin.math.min

context (View)
@Suppress("FunctionName")
inline fun ViewMeasure(
    widthSpec: Int,
    heightSpec: Int,
    desireWidth: Int,
    desireHeight: Int,
    onResult: (width: Int, height: Int) -> Unit,
) {
    val widthSize = MeasureSpec.getSize(widthSpec)
    val widthMode = MeasureSpec.getMode(widthSpec)
    val heightSize = MeasureSpec.getSize(heightSpec)
    val heightMode = MeasureSpec.getMode(heightSpec)

    val width =
        if (desireWidth == ViewGroup.LayoutParams.MATCH_PARENT) {
            widthSize
        } else {
            when (widthMode) {
                MeasureSpec.EXACTLY -> widthSize
                MeasureSpec.AT_MOST -> min(desireWidth.dp, widthSize)
                else -> desireWidth.dp
            }
        }

    val height =
        if (desireHeight == ViewGroup.LayoutParams.MATCH_PARENT) {
            heightSize
        } else {
            when (heightMode) {
                MeasureSpec.EXACTLY -> heightSize
                MeasureSpec.AT_MOST -> min(desireHeight.dp, heightSize)
                else -> desireHeight.dp
            }
        }

    onResult(width, height)
}
